<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\model\GoodsClassify;
use think\facade\Validate;
use think\response\Json;

class AdminGoodsClassify extends AdminBase
{

	protected $middleware = [
		'app\middleware\AdminLogin',
		'app\middleware\AdminAuth' => [
            'except' => ['parent']
        ]
	];

	private string $menuName = '商品分类';
    private int $maxLevel = 2;//最大分类级别

    /**
     * 显示资源列表
     * @throws
     * @return Json
     */
    public function index():Json
    {

		$data = GoodsClassify::where('parent_id',0)
			->order('sort','asc')
            ->select()->toArray();

        $this->nextList($data,'goods_classify');

		$this->result['data'] = $data;
		return returnAdmin($this->request,$this->result,$this->menuName.'-列表',$this->adminInfo);
    }

    /**
	 * 保存编辑的资源
	 * @throws
	 * @return Json
	 */
	public function save():Json
	{
		//获取form表单
		$param = input('param.',[]);

		$param = toUnderline($param);

		try{

			$model = new GoodsClassify();
			$fields = $model->getFields();
			$pk = $model->getPk();
			$id = $param[$pk] ?? 0;
			$rule = [
				'name' => 'require|max:64',
			];
			$message = [
				'name.require' => '分类名称必填',
				'name.max' => '分类名称最多64个字符'
			];
			$validate = Validate::rule($rule)->message($message);

			if(!$validate->check($param)){
				throw new \Exception($validate->getError());
			}
            $param['status'] = $param['status'] ?? 0;//防止开关不传值

			if(!$id){
                if($param['parent_id']){
                    $pm = $model->find($param['parent_id']);
                    if($pm){
                        if($pm['level'] >= $this->maxLevel){
                            throw new \Exception("最多只能创建{$this->maxLevel}级分类");
                        }
                        $param['level'] = $pm['level'] + 1;
                    }else{
                        $param['parent_id'] = 0;
                    }
                }
				//新增
				$model->create($param,$fields);
			}else{
				//修改
				$info = $model->find($id);
				if(!$info){
					throw new \Exception('无效参数');
				}

				$info->allowField($fields)->save($param);
			}

		}catch (\Exception $e){
			$this->result['code'] = 500;
			$this->result['msg'] = $e->getMessage();
		}
		return returnAdmin($this->request,$this->result,$this->menuName.'-编辑',$this->adminInfo);
	}

    /**
     * 删除指定资源
     * @throws
     * @return Json
     */
    public function delete():Json
    {

        $id = (string) input('id','');
        $ids = explode(',',$id);
		try {
			//批量删除
			if (count($ids) > 1) {
				GoodsClassify::destroy($ids);
			} else {
			//指定id删除
				$info = GoodsClassify::find($id);
				if (!$info) {
					throw new \Exception('无效参数');
				}
                //查询是否有子分类
                $count = GoodsClassify::where('parent_id',$id)->count();
                if($count){
                    throw new \Exception('请先删除所有子分类');
                }
                $logo = $info->getData('logo');
                $info->delete();
                //删除旧的图片文件
                if(is_file('.'.$logo)){
                    @unlink('.'.$logo);
                }
			}
			$this->result['msg'] = '删除ID：'.$id;
		}catch (\Exception $e){
			$this->result['code'] = 500;
			$this->result['msg'] = $e->getMessage();
		}

        return returnAdmin($this->request,$this->result,$this->menuName.'-删除',$this->adminInfo);
    }

    /**
     * 获取一级分类
     *
     * @throws
     * @return Json
     * */
    public function parent():Json
    {
        $level = input('level/d',1);
        if($level !== 0){
            $level = $this->maxLevel - 1;
        }
        $this->result['data'] = $this->getParent(0,$level);

        return jJson($this->result);
    }

    /**
     * 获取一级分类
     * @param int $pid 上级id
     * @param int $level 子级层数
     * @param string $field 查询字段
     * @throws
     * @return array
     * */
    public function getParent(int $pid = 0, int $level = 1, string $field = '*'):array
    {
        if(!$level){
            $level = $this->maxLevel;
        }
        $data = GoodsClassify::field($field)
            ->where('parent_id',$pid)
            ->where('status',1)
            ->where('level','<=',$level)
            ->order('sort','asc')
            ->select()->toArray();
        if(count($data)){
            foreach ($data as &$d){
                $d['children'] = $this->getParent($d['id'],$level,$field);
            }
        }
        return $data;
    }

}
